#!/bin/sh

encode() {
	if [ -z "$1" ]
	then
		salt=$(dd if=/dev/urandom count=9 bs=1 2>/dev/null | base64 | tr -d '=')
	else
		salt=$1
	fi
	cat - | argon2 "$salt" -id -t 3 -m 12 -p 1 -l 32 -e
}

verify() {
	stored=$1
	salt=$(echo "$stored" | cut -d '$' -f 5 | base64 -d)
	tested=$(cat - | encode "$salt")
	test "$stored" = "$tested"
}

if [ "$(basename "$0")" = 'password.sh' ]
then
	# dependency verification
	for cmd in argon2 base64
	do
		command -v $cmd >/dev/null || { echo "$0: \`$cmd\` not found"; exit 2; }
	done
	stty -echo
	cat - | encode "$1" > password
	stty echo
fi
